const { verifyJwtToken, createUserJwtToken } = require('../util/server_jwt');

module.exports = async function checkJWTMiddleWare(req, res, next) {
    let ptoken = req.headers.authorization;
    let ltoken = req.headers['x-refresh-token'];
    if (!ptoken) {
        res.status(400).json({ success: false, msg: "无效操作" });
        return ;
    } else {
        let result = await verifyJwtToken(ptoken);
        if (!result.login) {
            if (!ltoken) {
                res.status(400).json({ success: false, msg: "无效操作, 登录状态过期, 请重新登录" });
                return ;
            } else {
                let result = await verifyJwtToken(ltoken);
                if (!result.login) {
                    res.status(400).json({ success: false, msg: "无效操作, 登录状态过期, 请重新登录" });
                    return ;
                } else {
                    // 生成新的 ptoken
                    req.jwtResult = result;
                    let powerToken = await createUserJwtToken(result, {expiresIn: '20h'});
                    res.setHeader('Authorization', powerToken);
                }
            }
        } else {
            req.jwtResult = result;
        }
    }
    next();
}